import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import router from '../../router'

export interface TabItem {
  id: string
  title: string
  path: string
  query?: Record<string, any>
  params?: Record<string, any>
  closable?: boolean
  icon?: string
}

export const useTabsStore = defineStore('tabs', () => {
  // 状态
  const tabs = ref<TabItem[]>([])
  const activeTabId = ref<string>('')
  
  // 从本地存储恢复页签状态
  const restoreTabsFromStorage = () => {
    try {
      const savedTabs = localStorage.getItem('app-tabs')
      const savedActiveTabId = localStorage.getItem('app-active-tab-id')
      
      if (savedTabs) {
        tabs.value = JSON.parse(savedTabs)
      }
      
      if (savedActiveTabId) {
        activeTabId.value = savedActiveTabId
      }
    } catch (error) {
      console.warn('恢复页签状态失败:', error)
    }
  }
  
  // 保存页签状态到本地存储
  const saveTabsToStorage = () => {
    try {
      localStorage.setItem('app-tabs', JSON.stringify(tabs.value))
      localStorage.setItem('app-active-tab-id', activeTabId.value)
    } catch (error) {
      console.warn('保存页签状态失败:', error)
    }
  }

  // 计算属性
  const activeTab = computed(() => {
    return tabs.value.find(tab => tab.id === activeTabId.value)
  })

  const hasTabs = computed(() => tabs.value.length > 0)

  // 操作
  const addTab = (tab: TabItem) => {
    // 检查是否已存在相同的页签
    const existingTab = tabs.value.find(t => t.path === tab.path)
    if (existingTab) {
      // 如果已存在，激活该页签
      activeTabId.value = existingTab.id
      saveTabsToStorage()
      return existingTab
    }

    // 添加新页签
    tabs.value.push(tab)
    activeTabId.value = tab.id
    saveTabsToStorage()
    return tab
  }

  const removeTab = (tabId: string) => {
    const index = tabs.value.findIndex(tab => tab.id === tabId)
    if (index === -1) return

    const removedTab = tabs.value[index]
    tabs.value.splice(index, 1)

    // 如果删除的是当前激活的页签，需要激活其他页签
    if (activeTabId.value === tabId) {
      if (tabs.value.length > 0) {
        // 优先激活右侧的页签，如果没有则激活左侧的页签
        const nextIndex = index < tabs.value.length ? index : index - 1
        const nextTab = tabs.value[nextIndex]
        activeTabId.value = nextTab.id
        saveTabsToStorage()
        router.push(nextTab.path)
      } else {
        // 如果没有页签了，跳转到首页
        activeTabId.value = ''
        saveTabsToStorage()
        router.push('/dashboard')
      }
    } else {
      saveTabsToStorage()
    }
  }

  const setActiveTab = (tabId: string) => {
    const tab = tabs.value.find(t => t.id === tabId)
    if (tab) {
      activeTabId.value = tabId
      saveTabsToStorage()
      router.push(tab.path)
    }
  }

  const closeTab = (tabId: string) => {
    const tab = tabs.value.find(t => t.id === tabId)
    if (tab && tab.closable !== false) {
      removeTab(tabId)
    }
  }

  const closeOtherTabs = (keepTabId: string) => {
    const keepTab = tabs.value.find(t => t.id === keepTabId)
    if (keepTab) {
      tabs.value = [keepTab]
      activeTabId.value = keepTabId
      saveTabsToStorage()
      router.push(keepTab.path)
    }
  }

  const closeAllTabs = () => {
    tabs.value = []
    activeTabId.value = ''
    saveTabsToStorage()
    router.push('/dashboard')
  }

  const refreshTab = (tabId: string) => {
    const tab = tabs.value.find(t => t.id === tabId)
    if (tab) {
      // 通过重新导航来刷新页签
      router.push(tab.path)
    }
  }

  // 根据路由信息创建页签
  const createTabFromRoute = (route: any): TabItem => {
    const id = route.path + (route.query ? JSON.stringify(route.query) : '')
    return {
      id,
      title: route.meta?.title || route.name || '未知页面',
      path: route.path,
      query: route.query,
      params: route.params,
      closable: route.meta?.closable !== false,
      icon: route.meta?.icon
    }
  }

  // 初始化首页页签
  const initHomeTab = () => {
    // 先尝试从本地存储恢复
    restoreTabsFromStorage()
    
    // 如果没有页签或没有首页页签，则创建首页页签
    if (tabs.value.length === 0 || !tabs.value.find(tab => tab.path === '/dashboard')) {
      const homeTab: TabItem = {
        id: 'dashboard',
        title: '首页',
        path: '/dashboard',
        closable: false,
        icon: 'pi pi-home'
      }
      
      // 如果已有其他页签，在开头插入首页页签
      if (tabs.value.length > 0) {
        tabs.value.unshift(homeTab)
      } else {
        tabs.value = [homeTab]
      }
      
      // 如果当前没有激活的页签，激活首页
      if (!activeTabId.value) {
        activeTabId.value = homeTab.id
      }
      
      saveTabsToStorage()
    }
  }

  return {
    // 状态
    tabs,
    activeTabId,
    
    // 计算属性
    activeTab,
    hasTabs,
    
    // 操作
    addTab,
    removeTab,
    setActiveTab,
    closeTab,
    closeOtherTabs,
    closeAllTabs,
    refreshTab,
    createTabFromRoute,
    initHomeTab
  }
})
